<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="changeValue" />
        <!-- 树形组件 -->
        <!--  node-key="id" 添加唯一标识 -->
        <el-tree
          ref="treeRef"
          node-key="id"
          highlight-current
          :expand-on-click-node="false"
          default-expand-all
          :data="depts"
          :props="defaultProps"
          @current-change="handleTreeChange"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="add-employee" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>

          <el-button size="mini" @click="exportEmployee">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>

            </template>

          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>

              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>

              <el-button size="mini" type="text">删除</el-button>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>

      </div>

    </div>
    <!--导入excel  -->
    <importExcel :show-excel-dialog.sync="showExcelDialog" @updateSuccess="getDepartment" />
    <!-- 角色弹层组件 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>

          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>

        </el-col>

      </el-row>
    </el-dialog>
  </div>

</template>

<script>
import { getDepartment } from '@/api/department'
import { translateListToTreeData } from '@/utils'
import { assignRole, exportEmployee, getEmployeeDetail, getEmployeeList, getEnableRoleList } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        departmentId: null, // 部门id
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      list: [],
      total: 0,
      showExcelDialog: false, // 控制导入模板
      showRoleDialog: false, // 控制角色弹层
      roleList: [], // 角色列表
      roleIds: [], // 选中的角色id列表
      currentUserId: null // 记录选中的用户
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 确认分配角色
    async btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    // 点击角色控制弹层
    async btnRole(id) {
      // 1. 弹层显示 - 滞后
      // this.showRoleDialog = true
      // 2. 获取可用的角色列表 -> 显示到弹层上
      this.roleList = await getEnableRoleList()
      // 3. 记录点击的用户id
      this.currentUserId = id
      // 4. 基于id 获取员工详情 -> 拥有员工的角色信息
      const { roleIds } = await getEmployeeDetail(id)
      // 5. 赋值给选中的角色列表
      this.roleIds = roleIds
      // 调整顺序
      this.showRoleDialog = true
    },
    // 导出员工excel表
    async exportEmployee() {
      const loading = this.$loading({
        lock: true,
        text: '正在导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 1. 发送请求 - 导出员工信息
      const res = await exportEmployee()
      // console.log('员工信息数据', res)
      loading.close()
      // 2. 基于blob数据 -> 配合file-saver插件帮助我们下载
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    async getDepartment() {
      const res = await getDepartment()
      this.depts = translateListToTreeData(res, 0)
      // 初始化时 记录id
      console.log(this.depts)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中的节点 - 根节点 (传智教育)
      // 树形组件的渲染是异步的 $nextTick
      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(this.queryParams.departmentId)
      })
      // 获取员工列表 (所有)
      this.getEmployeeList()
    },
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList() // 查询数据
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 切换树形节点时 - 切换部门
    handleTreeChange(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置第一页
      //  获取员工列表 - 筛选
      this.getEmployeeList()
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    }
  }
}
</script>

    <style lang="scss" scoped>
    .app-container {
    background: #fff;
    display: flex;
    .left {
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .right {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin:10px ;
      }
      .username {
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04C9BE;
        font-size: 12px;
        display:inline-block;
      }
    }
  }

</style>
